import { Inject, Provide } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository, Between, Not, In, LessThan } from 'typeorm';
import { AppointmentInfoEntity } from '../entity/info';
import { CoolCommException } from '@cool-midway/core';
import { BaseSysUserEntity } from '../../base/entity/sys/user';
import { DictInfoEntity } from '../../dict/entity/info';
import { StudentStudentEntity } from '../../student/entity/student';
import { OrderInfoEntity } from '../../order/entity/info';
import { ClassInfoEntity } from '../../class/entity/info';
import { StudentInviteLogEntity } from '../../student/entity/inviteLog';
import { EyemanagerStudentEntity } from '../../../eyemanager/student/entity/student';
import { EyemanagerInviteLogEntity } from '../../../eyemanager/invite_log/entity/invite_log';
import { EyemanagerSalesEntity } from '../../../eyemanager/sales/entity/sales';
import { ProductProductEntity } from '../../product/entity/product';

import { exit } from 'process';

/**
 * 预约信息
 */
@Provide()
export class AppointmentBoardService extends BaseService {
  @InjectEntityModel(AppointmentInfoEntity)
  appointmentInfoEntity: Repository<AppointmentInfoEntity>;

  @InjectEntityModel(BaseSysUserEntity)
  baseSysUserEntity: Repository<BaseSysUserEntity>;

  @InjectEntityModel(DictInfoEntity)
  dictInfoEntity: Repository<DictInfoEntity>;

  @InjectEntityModel(StudentStudentEntity)
  studentStudentEntity: Repository<StudentStudentEntity>;

  @InjectEntityModel(OrderInfoEntity)
  OrderInfoEntity: Repository<OrderInfoEntity>;

  @InjectEntityModel(ClassInfoEntity)
  classInfoEntity: Repository<ClassInfoEntity>;

  @InjectEntityModel(StudentInviteLogEntity)
  studentInviteLogEntity: Repository<StudentInviteLogEntity>;

  @InjectEntityModel(EyemanagerStudentEntity)
  eyemanagerStudentEntity: Repository<EyemanagerStudentEntity>;

  @InjectEntityModel(EyemanagerInviteLogEntity)
  eyemanagerInviteLogEntity: Repository<EyemanagerInviteLogEntity>;

  @InjectEntityModel(EyemanagerSalesEntity)
  eyemanagerSalesEntity: Repository<EyemanagerSalesEntity>;

  @InjectEntityModel(ProductProductEntity)
  productProductEntity: Repository<ProductProductEntity>;

  @Inject()
  ctx;

  /**
   * 销售预约数据看板
   */
  async getSalesAppointConvertBoard(param: {
    startTime?: string; // 开始时间，可选
    endTime?: string;   // 结束时间，可选
  }) {
    // 初始化结果数组
    const result = [];

    // 处理时间范围
    let startDate = new Date();
    let endDate = new Date();
    
    if (param.startTime && param.endTime) {
      // 如果提供了时间范围，使用提供的时间
      startDate = new Date(param.startTime);
      endDate = new Date(param.endTime);
      endDate.setHours(23, 59, 59, 999);
    } else {
      // 默认最近7天
      startDate.setDate(startDate.getDate() - 6); // 减6天得到最近7天
      startDate.setHours(0, 0, 0, 0);
      endDate.setHours(23, 59, 59, 999);
    }

    // 获取预约数据
    const appointments = await this.appointmentInfoEntity.find({
      where: {
        appointmentTime: Between(startDate, endDate),
        appointmentStatus: Not(In([2, 4])) // 排除已取消的预约
      }
    });

    // 获取预约数据中的操作人ID
    const adminId = appointments.map(appointment => appointment.adminId);

    // 获取预约中的学员ID
    const studentIds = appointments.map(appointment => appointment.studentId);

    // 查询预约的学员
    const students = await this.studentStudentEntity.find({
      where: {
        id: In(studentIds), // 过滤出预约中的学员
      },
      select: ['id', 'source']  // 只选择ID和销售ID
    })

    // 将所有学员ID前面前面拼接100
    const prefixedStudentIds = studentIds.map(id => Number(`100${id}`));

    // 根据拼接后的学员ID查询邀请日志数据
    const inviteLogs = await this.studentInviteLogEntity.find({
      where: {
        salesId: In(prefixedStudentIds), // 使用拼接后的ID查询
      }
    })

    // 获取日期范围内的所有订单信息
    const ordersTemp = await this.OrderInfoEntity.find({
        where: {
            createTime: Between(startDate, endDate),
            status: 1  // 已支付的订单
        }
    });

    // 获取有效商品的Ids
    const products = await this.productProductEntity.find({
      where: {
        convertType: 1
      }
    });
    const productIds = products.map(p => p.id);
    // 过滤出订单中包含有效商品的订单
    const orders = ordersTemp.filter(order => {
      return order.ProductIds.some(detail => productIds.includes(detail));
    });

    // 获取订单数据中的学员ID
    const orderStudentIds = orders.map(order => order.userId);
    
    // 查询订单的学员，并且提取学员中的销售ID
    const orderStudents = await this.studentStudentEntity.find({
        where: {
            id: In(orderStudentIds),  // 过滤出订单中的学员
        },
        select: ['id', 'sales']  // 只选择ID和销售ID
    });

    // 获取销售ID
    const salesIds = orderStudents.map(student => student.sales);

    // 合并操作人ID和销售ID并且去重
    const uniqueIds = [...new Set([...adminId, ...salesIds])];

    // 根据ID获取用户信息
    const users = await this.baseSysUserEntity.find({
        where: {
            id: In(uniqueIds)  // 过滤出操作人和销售
        },
        select: ['id','name']  // 只选择ID和姓名
    });

    // 生成降序日期数组
    const dates = [];
    let currentDate = new Date(endDate);
    while (currentDate >= startDate) {
      dates.push(new Date(currentDate));
      currentDate.setDate(currentDate.getDate() - 1);
    }
    
    // 为每个门店和日期创建数据对象
    for (const user of users) {
      // 添加该店铺的合计行
      result.push({
        salesName: user.name, // 销售名称
        salesId: user.id, // 销售ID
        appoint: 0,  // 预约数
        sign: 0, // 到店数
        sign_rate: 0, // 到店率
        invite: 0, // 转介绍数
        invite_regist: 0, // 转介绍注册数
        invite_rate: 0, // 转介绍率
        invite_regist_rate: 0, // 转介绍注册率
        invite_source: 0, // 转介绍来源
        invite_source_rate: 0, // 转介绍来源率
        convert: 0, // 转化数
        money: 0, // 销售额
        single_money: 0,// 客单价
      });
    }

    // 提取预约数据中签到的学员ID，状态是1和5的
    const signedStudentIds = appointments.filter(appointment => appointment.appointmentStatus === 1 || appointment.appointmentStatus === 5).map(appointment => appointment.studentId);

    // 处理每个预约数据
    for (const appointment of appointments) {
      // 如果是签到的学员但没签到的数据，需要过滤掉
      if (signedStudentIds.includes(appointment.studentId) && appointment.appointmentStatus !== 1 && appointment.appointmentStatus !== 5) {
        continue; // 跳过这个预约数据
      }
      const salesData = result.find(d => d.salesId === appointment.adminId);
      
      if (salesData) {
        // 增加预约总数
        salesData.appoint++;

        // 找到对应的学员数据
        const student = students.find(student => student.id === appointment.studentId);
      
        if (student && student.source === 113) { // 检查是否是来自113的学员
          salesData.invite_source++; // 增加转介绍来源数
        }
        
        // 处理到店数据
        if (appointment.appointmentStatus === 1 || appointment.appointmentStatus === 5) {
          salesData.sign++;
        }
        // 拿到inviteLogs跟appointment.studentId一样的在inviteLogs中的所有数据，数组保存
        const logs = inviteLogs.filter(inviteLogs => inviteLogs.salesId === Number(`100${appointment.studentId}`));
        for (const log of logs) {
          if (log.behave === 0) { // 转介绍
            salesData.invite++;
          } else if (log.behave === 1) { // 转介绍注册
            salesData.invite_regist++;
          }
        }
      }
    }
  
    
    for (const data of result) {
      // 计算转介绍来源率
      if (data.appoint - data.invite_source === 0) {
        data.invite_source_rate = '0%'; // 避免除以0的情况
      } else {
        data.invite_source_rate = data.appoint > 0? `${(data.invite_source / (data.appoint - data.invite_source) * 100).toFixed(2)}%` : '0%';
      }
      // 计算转介绍率
      data.invite_rate = data.appoint > 0? `${(data.invite / data.appoint * 100).toFixed(2)}%` : '0%';
      // 计算转介绍注册率
      data.invite_regist_rate = data.appoint > 0? `${(data.invite_regist / data.appoint * 100).toFixed(2)}%` : '0%';
      // 计算到店率
      data.sign_rate = data.appoint > 0 ? `${(data.sign / data.appoint * 100).toFixed(2)}%` : '0%';
    }
  
    // 独立处理订单数据
    for (const order of orders) {
        const orderStudent = orderStudents.find(student => student.id === order.userId);
        if (!orderStudent) continue;

        const salesData = result.find(d => d.salesId === orderStudent.sales);
        
        if (salesData) {
            // 增加转化数
            salesData.convert++;

            // 增加销售额，保持 2 位小数
            const orderAmount = Number(order.payAmount || 0);
            salesData.money = Number((salesData.money + orderAmount).toFixed(2));

            // 计算客单价
            salesData.single_money = salesData.convert > 0 ? Math.round(salesData.money / salesData.convert) : 0;
        }
    }
    return result;
  }

  /**
   * 获取达人的销售数据
   */
  async getSalesAppointConvertBoardForDarenAction(param: {
    startTime?: string; // 开始时间，可选
    endTime?: string;   // 结束时间，可选
  }) {
    // 初始化结果数组
    let result = [];

    // 处理时间范围
    let startDate = new Date();
    let endDate = new Date();
    
    if (param.startTime && param.endTime) {
      // 如果提供了时间范围，使用提供的时间
      startDate = new Date(param.startTime);
      endDate = new Date(param.endTime);
      endDate.setHours(23, 59, 59, 999);
    } else {
      // 默认最近7天
      startDate.setDate(startDate.getDate() - 6); // 减6天得到最近7天
      startDate.setHours(0, 0, 0, 0);
      endDate.setHours(23, 59, 59, 999);
    }
    
    const sales = await this.eyemanagerSalesEntity.find({
      where: {
          status: 1
      }
    });
    const salesIds = sales.map(sales => sales.id);

    const invite_log = await this.eyemanagerInviteLogEntity.find({
      where: {
          sales_id: In(salesIds)  // 过滤出订单中的学员
      }
    });

    const sales_studentIds = invite_log.map(log => log.student_id);
    const sales_student = await this.eyemanagerStudentEntity.find({
      where: {
          id: In(sales_studentIds)  // 过滤出订单中的学员
      },
      select: ['id', 'phone']  // 只选择ID和销售ID
    });
    const sales_phone = sales_student.map(student => student.phone);
    const sales_new_student = await this.studentStudentEntity.find({
      where: {
          phone: In(sales_phone)  // 过滤出订单中的学员
      }
    });
    const sales_new_studentIds = sales_new_student.map(student => student.id);  

    // 获取预约数据
    const appointments = await this.appointmentInfoEntity.find({
      where: {
        createTime: Between(startDate, endDate),
        studentId: In(sales_new_studentIds)
      }
    });


    // 获取预约中的学员ID
    const studentIds = appointments.map(appointment => appointment.studentId);

    // 查询预约的学员
    const students = await this.studentStudentEntity.find({
      where: {
        id: In(studentIds), // 过滤出预约中的学员
      },
      select: ['id', 'phone']  // 只选择ID和销售ID
    })

    // 将所有学员ID前面前面拼接100
    const prefixedStudentIds = studentIds.map(id => Number(`100${id}`));

    // 根据拼接后的学员ID查询邀请日志数据
    const inviteLogs = await this.eyemanagerInviteLogEntity.find({
      where: {
        sales_id: In(prefixedStudentIds), // 使用拼接后的ID查询
      }
    })

    // 获取日期范围内的所有订单信息
    const ordersTemp = await this.OrderInfoEntity.find({
        where: {
            createTime: Between(startDate, endDate),
            status: 1,  // 已支付的订单
            userId: In(sales_new_studentIds)
        }
    });

    // 获取有效商品的Ids
    const products = await this.productProductEntity.find({
      where: {
        convertType: 1
      }
    });
    const productIds = products.map(p => p.id);
    // 过滤出订单中包含有效商品的订单
    const orders = ordersTemp.filter(order => {
      return order.ProductIds.some(detail => productIds.includes(detail));
    });

    // 获取订单数据中的学员ID
    const orderStudentIds = orders.map(order => order.userId);
    
    // 查询订单的学员，并且提取学员中的销售ID
    const orderStudents = await this.studentStudentEntity.find({
        where: {
            id: In(orderStudentIds),  // 过滤出订单中的学员
        },
        select: ['id', 'phone']  // 只选择ID和销售ID
    });


    
    // 为每个达人和日期创建数据对象
    for (const user of sales) {
      // 在invite_log中找到所有的sales_id等于user.id的记录
      const userInviteLogs = invite_log.filter(log => log.sales_id == user.id);
      // 提取所有的student_id
      const logStudentIds = userInviteLogs.map(log => log.student_id);
      // 在eyemanagerStudent中找到所有的id等于logStudentIds的记录
      const logStudents = sales_student.filter(student => logStudentIds.includes(Number(student.id)));
      // 提取所有的phone
      const logStudentPhones = logStudents.map(student => student.phone);

      const nameArr = user.name.split('-');
      let upSales = user.name;
      let downSales = '';
      if (nameArr.length > 0) {
        upSales = nameArr[0];
        for (let i = 1; i < nameArr.length; i++) {
          downSales += `${nameArr[i]}`;
        }
      }
      
      // 添加该店铺的合计行
      result.push({
        salesName: user.name, // 销售名称
        upSales: upSales, // 上级销售名称
        downSales: downSales, // 下级销售名称
        salesId: user.id, // 销售ID
        appoint: 0,  // 预约数
        cancelAppoint: 0,// 取消预约数
        validAppoint: 0, // 有效预约数
        sign: 0, // 到店数
        sign_rate: 0, // 到店率
        invite: 0, // 转介绍数
        invite_regist: 0, // 转介绍注册数
        invite_rate: 0, // 转介绍率
        invite_regist_rate: 0, // 转介绍注册率
        invite_source: 0, // 转介绍来源
        invite_source_rate: 0, // 转介绍来源率
        convert: 0, // 转化数
        money: 0, // 销售额
        single_money: 0,// 客单价
        studentPhones: logStudentPhones, // 转介绍注册数
      });
    }
    result.sort((a, b) => {
      const aPrefix = a.salesName.split('-')[0];
      const bPrefix = b.salesName.split('-')[0];
      return aPrefix.localeCompare(bPrefix);
    });

    // 提取预约数据中签到的学员ID
    // const signedStudentIds = appointments.filter(appointment => appointment.appointmentStatus === 1 || appointment.appointmentStatus === 5).map(appointment => appointment.studentId);

    // 处理每个预约数据
    for (const appointment of appointments) {
      // 如果是签到的学员但没签到的数据，需要过滤掉
      // if (signedStudentIds.includes(appointment.studentId) && appointment.appointmentStatus !== 1 && appointment.appointmentStatus !== 5) {
      //   continue; // 跳过这个预约数据
      // }
      // 在students中找到所有的id等于appointment.studentId的记录
      const appointStudent = students.find(student => student.id === appointment.studentId);
      // 在result中找到studentPhone包含apointtStudent.phone的记录
      const salesData = result.find(student => student.studentPhones.includes(appointStudent.phone));
      if (!salesData) continue;
      
      if (salesData) {
        // 增加预约总数
        salesData.appoint++;
        if (appointment.appointmentStatus === 2 || appointment.appointmentStatus === 4) {
          salesData.cancelAppoint++;
        } else {
          salesData.validAppoint++;
        }
        // 找到对应的学员数据
        const student = students.find(student => student.id === appointment.studentId);
      
        if (student && student.source === 113) { // 检查是否是来自113的学员
          salesData.invite_source++; // 增加转介绍来源数
        }
        
        // 处理到店数据
        if (appointment.appointmentStatus === 1 || appointment.appointmentStatus === 5) {
          salesData.sign++;
        }
        // 拿到inviteLogs跟appointment.studentId一样的在inviteLogs中的所有数据，数组保存
        const logs = inviteLogs.filter(inviteLogs => inviteLogs.sales_id === Number(`100${appointment.studentId}`));
        for (const log of logs) {
          if (log.behave === 0) { // 转介绍
            salesData.invite++;
          } else if (log.behave === 1) { // 转介绍注册
            salesData.invite_regist++;
          }
        }
      }
    }
  
    
    for (const data of result) {
      // 计算转介绍来源率
      if (data.appoint - data.invite_source === 0) {
        data.invite_source_rate = '0%'; // 避免除以0的情况
      } else {
        data.invite_source_rate = data.appoint > 0? `${(data.invite_source / (data.appoint - data.invite_source) * 100).toFixed(2)}%` : '0%';
      }
      // 计算转介绍率
      data.invite_rate = data.appoint > 0? `${(data.invite / data.appoint * 100).toFixed(2)}%` : '0%';
      // 计算转介绍注册率
      data.invite_regist_rate = data.appoint > 0? `${(data.invite_regist / data.appoint * 100).toFixed(2)}%` : '0%';
      // 计算到店率
      data.sign_rate = data.appoint > 0 ? `${(data.sign / data.appoint * 100).toFixed(2)}%` : '0%';
    }
  
    // 独立处理订单数据
    for (const order of orders) {
        const orderStudent = orderStudents.find(student => student.id === order.userId);
        if (!orderStudent) continue;

        // 在result中找到studentPhone包含apointtStudent.phone的记录
        const salesData = result.find(student => student.studentPhones.includes(orderStudent.phone));
        
        if (salesData) {
            // 增加转化数
            salesData.convert++;

            // 增加销售额，保持 2 位小数
            const orderAmount = Number(order.payAmount || 0);
            salesData.money = Number((salesData.money + orderAmount).toFixed(2));

            // 计算客单价
            salesData.single_money = salesData.convert > 0 ? Math.round(salesData.money / salesData.convert) : 0;
        }
    }

    if (Array.isArray(result)) {
      result.sort((a, b) => b.appoint - a.appoint);
    }    

    // 过滤掉appoint和order都为0的记录
    const newResult = [];
    for (const data of result) {
      if (data.appoint === 0 && data.convert === 0) {
        continue;
      }
      newResult.push(data);
    }

    
    
    return newResult;
  }

  /**
   * 获取达人的销售数据
   */
  async getSalesAppointConvertBoardForDaren(param: {
    startTime?: string; // 开始时间，可选
    endTime?: string;   // 结束时间，可选
  }) {
    // 初始化结果数组
    let result = [];

    // 处理时间范围
    let startDate = new Date();
    let endDate = new Date();
    
    if (param.startTime && param.endTime) {
      // 如果提供了时间范围，使用提供的时间
      startDate = new Date(param.startTime);
      endDate = new Date(param.endTime);
      endDate.setHours(23, 59, 59, 999);
    } else {
      // 默认最近7天
      startDate.setDate(startDate.getDate() - 6); // 减6天得到最近7天
      startDate.setHours(0, 0, 0, 0);
      endDate.setHours(23, 59, 59, 999);
    }
    
    const sales = await this.eyemanagerSalesEntity.find({
      where: {
          status: 1
      }
    });
    const salesIds = sales.map(sales => sales.id);

    const invite_log = await this.eyemanagerInviteLogEntity.find({
      where: {
          sales_id: In(salesIds)  // 过滤出订单中的学员
      }
    });

    const sales_studentIds = invite_log.map(log => log.student_id);
    const sales_student = await this.eyemanagerStudentEntity.find({
      where: {
          id: In(sales_studentIds)  // 过滤出订单中的学员
      },
      select: ['id', 'phone']  // 只选择ID和销售ID
    });
    const sales_phone = sales_student.map(student => student.phone);
    const sales_new_student = await this.studentStudentEntity.find({
      where: {
          phone: In(sales_phone)  // 过滤出订单中的学员
      }
    });
    const sales_new_studentIds = sales_new_student.map(student => student.id);  

    // 获取预约数据
    const appointments = await this.appointmentInfoEntity.find({
      where: {
        appointmentTime: Between(startDate, endDate),
        appointmentStatus: Not(In([2, 4])), // 排除已取消的预约
        studentId: In(sales_new_studentIds)
      }
    });


    // 获取预约中的学员ID
    const studentIds = appointments.map(appointment => appointment.studentId);

    // 查询预约的学员
    const students = await this.studentStudentEntity.find({
      where: {
        id: In(studentIds), // 过滤出预约中的学员
      },
      select: ['id', 'phone']  // 只选择ID和销售ID
    })

    // 将所有学员ID前面前面拼接100
    const prefixedStudentIds = studentIds.map(id => Number(`100${id}`));

    // 根据拼接后的学员ID查询邀请日志数据
    const inviteLogs = await this.eyemanagerInviteLogEntity.find({
      where: {
        sales_id: In(prefixedStudentIds), // 使用拼接后的ID查询
      }
    })

    // 获取日期范围内的所有订单信息
    const ordersTemp = await this.OrderInfoEntity.find({
        where: {
            createTime: Between(startDate, endDate),
            status: 1,  // 已支付的订单
            userId: In(sales_new_studentIds)
        }
    });

    // 获取有效商品的Ids
    const products = await this.productProductEntity.find({
      where: {
        convertType: 1
      }
    });
    const productIds = products.map(p => p.id);
    // 过滤出订单中包含有效商品的订单
    const orders = ordersTemp.filter(order => {
      return order.ProductIds.some(detail => productIds.includes(detail));
    });

    // 获取订单数据中的学员ID
    const orderStudentIds = orders.map(order => order.userId);
    
    // 查询订单的学员，并且提取学员中的销售ID
    const orderStudents = await this.studentStudentEntity.find({
        where: {
            id: In(orderStudentIds),  // 过滤出订单中的学员
        },
        select: ['id', 'phone']  // 只选择ID和销售ID
    });


    
    // 为每个达人和日期创建数据对象
    for (const user of sales) {
      // 在invite_log中找到所有的sales_id等于user.id的记录
      const userInviteLogs = invite_log.filter(log => log.sales_id == user.id);
      // 提取所有的student_id
      const logStudentIds = userInviteLogs.map(log => log.student_id);
      // 在eyemanagerStudent中找到所有的id等于logStudentIds的记录
      const logStudents = sales_student.filter(student => logStudentIds.includes(Number(student.id)));
      // 提取所有的phone
      const logStudentPhones = logStudents.map(student => student.phone);

      const nameArr = user.name.split('-');
      let upSales = user.name;
      let downSales = '';
      if (nameArr.length > 0) {
        upSales = nameArr[0];
        for (let i = 1; i < nameArr.length; i++) {
          downSales += `${nameArr[i]}`;
        }
      }
      
      // 添加该店铺的合计行
      result.push({
        salesName: user.name, // 销售名称
        upSales: upSales, // 上级销售名称
        downSales: downSales, // 下级销售名称
        salesId: user.id, // 销售ID
        appoint: 0,  // 预约数
        sign: 0, // 到店数
        sign_rate: 0, // 到店率
        invite: 0, // 转介绍数
        invite_regist: 0, // 转介绍注册数
        invite_rate: 0, // 转介绍率
        invite_regist_rate: 0, // 转介绍注册率
        invite_source: 0, // 转介绍来源
        invite_source_rate: 0, // 转介绍来源率
        convert: 0, // 转化数
        money: 0, // 销售额
        single_money: 0,// 客单价
        studentPhones: logStudentPhones, // 转介绍注册数
      });
    }
    result.sort((a, b) => {
      const aPrefix = a.salesName.split('-')[0];
      const bPrefix = b.salesName.split('-')[0];
      return aPrefix.localeCompare(bPrefix);
    });

    // 提取预约数据中签到的学员ID
    const signedStudentIds = appointments.filter(appointment => appointment.appointmentStatus === 1 || appointment.appointmentStatus === 5).map(appointment => appointment.studentId);

    // 处理每个预约数据
    for (const appointment of appointments) {
      // 如果是签到的学员但没签到的数据，需要过滤掉
      if (signedStudentIds.includes(appointment.studentId) && appointment.appointmentStatus !== 1 && appointment.appointmentStatus !== 5) {
        continue; // 跳过这个预约数据
      }
      // 在students中找到所有的id等于appointment.studentId的记录
      const appointStudent = students.find(student => student.id === appointment.studentId);
      // 在result中找到studentPhone包含apointtStudent.phone的记录
      const salesData = result.find(student => student.studentPhones.includes(appointStudent.phone));
      if (!salesData) continue;
      
      if (salesData) {
        // 增加预约总数
        salesData.appoint++;

        // 找到对应的学员数据
        const student = students.find(student => student.id === appointment.studentId);
      
        if (student && student.source === 113) { // 检查是否是来自113的学员
          salesData.invite_source++; // 增加转介绍来源数
        }
        
        // 处理到店数据
        if (appointment.appointmentStatus === 1 || appointment.appointmentStatus === 5) {
          salesData.sign++;
        }
        // 拿到inviteLogs跟appointment.studentId一样的在inviteLogs中的所有数据，数组保存
        const logs = inviteLogs.filter(inviteLogs => inviteLogs.sales_id === Number(`100${appointment.studentId}`));
        for (const log of logs) {
          if (log.behave === 0) { // 转介绍
            salesData.invite++;
          } else if (log.behave === 1) { // 转介绍注册
            salesData.invite_regist++;
          }
        }
      }
    }
  
    
    for (const data of result) {
      // 计算转介绍来源率
      if (data.appoint - data.invite_source === 0) {
        data.invite_source_rate = '0%'; // 避免除以0的情况
      } else {
        data.invite_source_rate = data.appoint > 0? `${(data.invite_source / (data.appoint - data.invite_source) * 100).toFixed(2)}%` : '0%';
      }
      // 计算转介绍率
      data.invite_rate = data.appoint > 0? `${(data.invite / data.appoint * 100).toFixed(2)}%` : '0%';
      // 计算转介绍注册率
      data.invite_regist_rate = data.appoint > 0? `${(data.invite_regist / data.appoint * 100).toFixed(2)}%` : '0%';
      // 计算到店率
      data.sign_rate = data.appoint > 0 ? `${(data.sign / data.appoint * 100).toFixed(2)}%` : '0%';
    }
  
    // 独立处理订单数据
    for (const order of orders) {
        const orderStudent = orderStudents.find(student => student.id === order.userId);
        if (!orderStudent) continue;

        // 在result中找到studentPhone包含apointtStudent.phone的记录
        const salesData = result.find(student => student.studentPhones.includes(orderStudent.phone));
        
        if (salesData) {
            // 增加转化数
            salesData.convert++;

            // 增加销售额，保持 2 位小数
            const orderAmount = Number(order.payAmount || 0);
            salesData.money = Number((salesData.money + orderAmount).toFixed(2));

            // 计算客单价
            salesData.single_money = salesData.convert > 0 ? Math.round(salesData.money / salesData.convert) : 0;
        }
    }

    if (Array.isArray(result)) {
      result.sort((a, b) => b.appoint - a.appoint);
    }    

    // 过滤掉appoint和order都为0的记录
    const newResult = [];
    for (const data of result) {
      if (data.appoint === 0 && data.convert === 0) {
        continue;
      }
      newResult.push(data);
    }

    
    
    return newResult;
  }
}